﻿using DuckDB.NET.Data;
using System;
using System.Data.Common;

namespace RPAAction.Data_CSO
{
    public class DuckDbDataReader : RPADataReader
    {
        private DuckDBConnection connection;
        private DuckDbCommand command;
        private DuckDBDataReader reader;
        private bool isClosed = false;

        public DuckDbDataReader(string dbPath, string SQL)
        {
            this.connection = new DuckDBConnection($"Data Source={dbPath};");
            connection.Open();
            this.command = new DuckDbCommand(SQL, connection);
            this.reader = command.ExecuteReader();
        }

        public override int FieldCount => reader.FieldCount;

        public override bool IsClosed => isClosed;

        public override bool HasRows => reader.HasRows;

        public override void Close()
        {
            if (reader != null)
            {
                reader.Close();
                reader = null;
            }
            if (command != null)
            {
                command.Dispose();
                command = null;
            }
            if (connection != null)
            {
                connection.Close();
                connection = null;
            }
            isClosed = true;
        }

        public override string GetName(int ordinal)
        {
            return reader.GetName(ordinal);
        }

        public override object GetValue(int ordinal)
        {
            return reader.GetValue(ordinal);
        }

        public override bool Read()
        {
            return reader.Read();
        }
    }
}
